package api

import (
	"context"
	"fmt"
	"github.com/kadycui/fiber-ci/pkg/cache"
	"github.com/kadycui/fiber-ci/pkg/database"
	"net/http"

	"github.com/gofiber/fiber/v2"
	"github.com/kadycui/fiber-ci/model"
	"github.com/kadycui/fiber-ci/serialize"
)

// GetLuById is a function to get a Lu by ID
// @Summary 通过ID获取一个Lu详情
// @Description 通过ID一个Lu详情
// @Tags Lu
// @Accept json
// @Produce json
// @Param id path int true "Lu ID"
// @Success 200 {object} serialize.ResponseHTTP{data=[]model.Lu}
// @Failure 404 {object} serialize.ResponseHTTP{}
// @Failure 503 {object} serialize.ResponseHTTP{}
// @Router /v1/lu/{id} [get]
func GetLuById(c *fiber.Ctx) error {
	id := c.Params("id")
	db := database.DB
	rdb := cache.RDB

	lu := new(model.Lu)
	if err := db.First(&lu, id).Error; err != nil {
		switch err.Error() {
		case "record not found":
			return c.Status(http.StatusNotFound).JSON(serialize.ResponseHTTP{
				Success: false,
				Message: fmt.Sprintf("Lu with ID %v not found.", id),
				Data:    nil,
			})
		default:
			return c.Status(http.StatusServiceUnavailable).JSON(serialize.ResponseHTTP{
				Success: false,
				Message: err.Error(),
				Data:    nil,
			})

		}
	}

	cl := lu.GetCacheLu()

	// 存储到 Redis
	err := serialize.SetCache(context.Background(), rdb, id, "lu", cl)
	if err != nil {
		panic(err)
	}

	return c.JSON(serialize.ResponseHTTP{
		Success: true,
		Message: "Success get Lu by ID.",
		Data:    *lu,
	})

}
